import React, { useState, useEffect } from 'react';
import { useParams, useNavigate, useLocation } from 'react-router-dom';
import { ChapterTitle } from './ChapterTitle';
import { Paragraph } from './Paragraph';
import { books } from '../data/books';
import { SpeedControl } from './SpeedControl';
import { getSpeed, setSpeed } from '../utils/textToSpeech';

// 定义页码项的类型
type PageItem = {
    type: 'page' | 'ellipsis';
    value: number;
};

export const Reader: React.FC = () => {
    const navigate = useNavigate();
    const { bookId, chapterId } = useParams();
    const location = useLocation();
    const searchParams = new URLSearchParams(location.search);
    const bookmarkParam = searchParams.get('bookmark');
    
    const [bookmark, setBookmark] = useState<number | null>(() => {
        const saved = localStorage.getItem(`bookmark-${bookId}`);
        if (saved) {
            const { chapterId: savedChapterId, index } = JSON.parse(saved);
            return savedChapterId === chapterId ? index : null;
        }
        return null;
    });

    const [showButtons, setShowButtons] = useState(false);
    let scrollTimeout: NodeJS.Timeout;
    const [speed, setSpeedState] = useState(getSpeed());
    const [currentPage, setCurrentPage] = useState(1);
    const itemsPerPage = 10;

    useEffect(() => {
        const handleScroll = () => {
            if (window.scrollY > 300) {
                setShowButtons(true);

                if (scrollTimeout) {
                    clearTimeout(scrollTimeout);
                }

                scrollTimeout = setTimeout(() => {
                    setShowButtons(false);
                }, 4000);
            } else {
                setShowButtons(false);
            }
        };

        window.addEventListener('scroll', handleScroll);
        return () => {
            window.removeEventListener('scroll', handleScroll);
            if (scrollTimeout) {
                clearTimeout(scrollTimeout);
            }
        };
    }, []);

    const scrollToTop = () => {
        window.scrollTo({ top: 0, behavior: 'smooth' });
    };

    // 找到当前书籍和章节
    const book = books.find(b => b.id === bookId);
    const chapter = book?.chapters.find(c => c.id === chapterId);

    const handleToggleBookmark = (index: number) => {
        if (bookmark === index) {
            setBookmark(null);
            localStorage.removeItem(`bookmark-${bookId}`);
        } else {
            setBookmark(index);
            localStorage.setItem(`bookmark-${bookId}`, JSON.stringify({
                chapterId,
                index,
                timestamp: Date.now()
            }));
        }
    };

    useEffect(() => {
        // 在组件挂载时添加遮罩层
        const overlay = document.createElement('div');
        overlay.className = 'fixed inset-0 bg-white z-50';
        document.body.appendChild(overlay);

        // 使用 requestAnimationFrame 确保内容渲染后再移除遮罩层
        requestAnimationFrame(() => {
            requestAnimationFrame(() => {
                if (document.body.contains(overlay)) {
                    document.body.removeChild(overlay);
                }
            });
        });

        return () => {
            if (document.body.contains(overlay)) {
                document.body.removeChild(overlay);
            }
        };
    }, []);

    const scrollToBookmark = () => {
        if (bookmark !== null) {
            // 计算书签所在的页码
            const bookmarkPage = Math.floor(bookmark / itemsPerPage) + 1;
            // 先切换到对应页码
            setCurrentPage(bookmarkPage);
            // 使用 setTimeout 确保页面内容已经更新
            setTimeout(() => {
                const element = document.getElementById(`bookmark-${bookmark}`);
                if (element) {
                    element.scrollIntoView({ 
                        behavior: 'smooth',
                        block: 'center'
                    });
                }
            }, 100);
        }
    };

    const handleSpeedChange = (newSpeed: number) => {
        setSpeed(newSpeed);
        setSpeedState(newSpeed);
    };

    // 计算当前页的内容
    const getCurrentPageContent = () => {
        if (!chapter) return [];
        const startIndex = (currentPage - 1) * itemsPerPage;
        const endIndex = startIndex + itemsPerPage;
        return chapter.content.slice(startIndex, endIndex);
    };

    // 计算总页数
    const totalPages = Math.ceil((chapter?.content.length || 0) / itemsPerPage);

    // 页面导航函数
    const goToPage = (page: number) => {
        setCurrentPage(page);
        window.scrollTo({ top: 0, behavior: 'smooth' });
    };

    // 修改 getPageRange 函数的返回类型
    const getPageRange = (): PageItem[] => {
        const range: PageItem[] = [];
        
        // 总是显示第一页
        range.push({
            type: 'page',
            value: 1
        });

        // 计算当前页码附近的范围
        let start = Math.max(1, currentPage - 2);
        let end = Math.min(totalPages, start + 4);
        
        // 如果当前页靠近末尾，调整显示范围
        if (end - start < 4) {
            start = Math.max(1, end - 4);
        }

        // 添加第一个省略号和中间页码
        if (start > 2) {
            // 修改这里：前面的省略号点击后跳转到前一组的中间页码
            const prevGroupEnd = start - 1;
            const prevGroupStart = Math.max(2, prevGroupEnd - 4);
            const prevGroupMiddle = Math.floor((prevGroupStart + prevGroupEnd) / 2);
            
            range.push({
                type: 'ellipsis',
                value: prevGroupMiddle
            });

            // 从当前页码组的第一个开始
            for (let i = start; i <= end; i++) {
                range.push({
                    type: 'page',
                    value: i
                });
            }
        } else {
            // 直接添加从2开始的页码
            for (let i = 2; i <= end; i++) {
                range.push({
                    type: 'page',
                    value: i
                });
            }
        }

        // 添加最后的省略号和末页
        if (end < totalPages - 1) {
            // 修改这里：后面的省略号点击后跳转到后一组的中间页码
            const nextGroupStart = end + 1;
            const nextGroupEnd = Math.min(totalPages - 1, nextGroupStart + 4);
            const nextGroupMiddle = Math.floor((nextGroupStart + nextGroupEnd) / 2);

            range.push({
                type: 'ellipsis',
                value: nextGroupMiddle
            });
            range.push({
                type: 'page',
                value: totalPages
            });
        } else if (end < totalPages) {
            range.push({
                type: 'page',
                value: totalPages
            });
        }

        return range;
    };

    useEffect(() => {
        // 如果 URL 中有书签参数，跳转到对应段落
        if (bookmarkParam) {
            const bookmarkIndex = parseInt(bookmarkParam, 10);
            const bookmarkPage = Math.floor(bookmarkIndex / itemsPerPage) + 1;
            setCurrentPage(bookmarkPage);
            
            // 等待页面渲染后滚动到书签位置
            setTimeout(() => {
                const element = document.getElementById(`bookmark-${bookmarkIndex}`);
                if (element) {
                    element.scrollIntoView({ 
                        behavior: 'smooth',
                        block: 'center'
                    });
                }
            }, 100);
        }
    }, [bookmarkParam]);

    if (!chapter) {
        return <div className="p-6">Chapter not found</div>;
    }

    return (
        <div className="relative">
            {/* 固定在顶部的导航栏 */}
            <div className="fixed top-0 left-0 right-0 bg-white shadow-md z-50">
                <div className="max-w-4xl mx-auto px-6 py-3 flex items-center justify-between">
                    <button
                        onClick={() => navigate(-1)}
                        className="flex items-center space-x-2 text-gray-600 hover:text-gray-800"
                    >
                        <svg
                            className="w-5 h-5"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                        >
                            <path
                                strokeLinecap="round"
                                strokeLinejoin="round"
                                strokeWidth={2}
                                d="M15 19l-7-7 7-7"
                            />
                        </svg>
                        <span>返回</span>
                    </button>

                    <div className="text-gray-800 font-medium truncate mx-4">
                        {chapter.number} · {chapter.titleEnglish}
                    </div>

                    <SpeedControl 
                        speed={speed}
                        onSpeedChange={handleSpeedChange}
                    />
                </div>
            </div>

            {/* 主要内容，添加顶部padding以避免被固定导航栏遮挡 */}
            <div className="max-w-4xl mx-auto p-6 pt-16">
                <div className="bg-white shadow-lg relative">
                    <ChapterTitle
                        chapterNumber={chapter.number}
                        english={chapter.titleEnglish}
                        chinese={chapter.titleChinese}
                        onScrollToBookmark={scrollToBookmark}
                        hasBookmark={bookmark !== null}
                    />

                    {getCurrentPageContent().map((p, index) => {
                        const absoluteIndex = (currentPage - 1) * itemsPerPage + index;
                        return (
                            <Paragraph
                                key={absoluteIndex}
                                index={absoluteIndex}
                                english={p.english}
                                chinese={p.chinese}
                                isBookmarked={bookmark === absoluteIndex}
                                onToggleBookmark={handleToggleBookmark}
                            />
                        );
                    })}

                    {/* 分页控制 */}
                    <div className="flex justify-center items-center gap-1 py-6">
                        <button
                            onClick={() => goToPage(currentPage - 1)}
                            disabled={currentPage === 1}
                            className={`px-3 py-2 rounded-sm ${
                                currentPage === 1 
                                    ? 'bg-gray-200 text-gray-400 cursor-not-allowed' 
                                    : 'bg-white text-gray-600 hover:bg-blue-50 hover:text-blue-600'
                            } border transition-colors duration-200`}
                            aria-label="上一页"
                        >
                            <svg
                                className="w-4 h-4"
                                fill="none"
                                stroke="currentColor"
                                viewBox="0 0 24 24"
                            >
                                <path
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                    strokeWidth={2}
                                    d="M15 19l-7-7 7-7"
                                />
                            </svg>
                        </button>

                        {getPageRange().map((item, index) => (
                            <button
                                key={`page-${index}`}
                                onClick={() => goToPage(item.value)}
                                className={`w-8 h-8 rounded-sm ${
                                    currentPage === item.value
                                        ? 'bg-blue-600 text-white'
                                        : 'bg-[#F4F4F5] text-gray-600 hover:bg-blue-50 hover:text-blue-600'
                                } border transition-colors duration-200 ${
                                    item.type === 'ellipsis' ? 'font-bold' : ''
                                }`}
                            >
                                {item.type === 'ellipsis' ? '...' : item.value}
                            </button>
                        ))}

                        <button
                            onClick={() => goToPage(currentPage + 1)}
                            disabled={currentPage === totalPages}
                            className={`px-3 py-2 rounded-sm ${
                                currentPage === totalPages 
                                    ? 'bg-gray-200 text-gray-400 cursor-not-allowed' 
                                    : 'bg-white text-gray-600 hover:bg-blue-50 hover:text-blue-600'
                            } border transition-colors duration-200`}
                            aria-label="下一页"
                        >
                            <svg
                                className="w-4 h-4"
                                fill="none"
                                stroke="currentColor"
                                viewBox="0 0 24 24"
                            >
                                <path
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                    strokeWidth={2}
                                    d="M9 5l7 7-7 7"
                                />
                            </svg>
                        </button>
                    </div>

                    <div className="flex justify-center gap-4 pb-6">
                        <button
                            onClick={() => navigate(-1)}
                            className="bg-gray-100 hover:bg-gray-200 text-gray-600 px-4 py-2 rounded-full flex items-center space-x-1 transition-colors duration-200"
                        >
                            <svg
                                className="w-5 h-5"
                                fill="none"
                                stroke="currentColor"
                                viewBox="0 0 24 24"
                            >
                                <path
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                    strokeWidth={2}
                                    d="M15 19l-7-7 7-7"
                                />
                            </svg>
                            <span>返回上一页</span>
                        </button>
                        <button
                            onClick={scrollToTop}
                            className="bg-gray-100 hover:bg-gray-200 text-gray-600 px-4 py-2 rounded-full flex items-center space-x-1 transition-colors duration-200"
                        >
                            <svg
                                className="w-5 h-5"
                                fill="none"
                                stroke="currentColor"
                                viewBox="0 0 24 24"
                            >
                                <path
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                    strokeWidth={2}
                                    d="M5 10l7-7m0 0l7 7m-7-7v18"
                                />
                            </svg>
                            <span>返回顶部</span>
                        </button>
                    </div>
                </div>
            </div>

            {/* 保持原有的右侧浮动按钮 */}
            {/* <div
                className={`fixed transition-opacity duration-300 ${showButtons ? 'opacity-100' : 'opacity-0 pointer-events-none'
                    }`}
                style={{
                    top: '80vh',
                    right: 'min(calc(50% + 512px - 56px - 10px), calc(100% - 56px - 24px))'
                }}
            >
                <button
                    onClick={() => navigate(-1)}
                    className="bg-white shadow-lg rounded-full p-3 hover:bg-gray-100 transition-colors duration-200"
                    aria-label="返回"
                >
                    <svg
                        className="w-6 h-6 text-gray-600"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                    >
                        <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            strokeWidth={2}
                            d="M15 19l-7-7 7-7"
                        />
                    </svg>
                </button>
            </div> */}

            {showButtons && (
                <div
                    className={`fixed transition-opacity duration-300 ${showButtons ? 'opacity-100' : 'opacity-0 pointer-events-none'
                        }`}
                    style={{
                        top: '80vh',
                        left: 'min(calc(50% + 512px - 56px - 10px), calc(100% - 56px - 24px))'
                    }}
                >
                    <button
                        onClick={scrollToTop}
                        className="bg-white shadow-lg rounded-full p-3 hover:bg-gray-100 transition-colors duration-200"
                        aria-label="返回顶部"
                    >
                        <svg
                            className="w-6 h-6 text-gray-600"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                        >
                            <path
                                strokeLinecap="round"
                                strokeLinejoin="round"
                                strokeWidth={2}
                                d="M5 10l7-7m0 0l7 7m-7-7v18"
                            />
                        </svg>
                    </button>
                </div>
            )}
        </div>
    );
}; 